package com.example;

import java.util.function.Function;
import java.util.function.IntBinaryOperator;
import java.util.function.IntConsumer;
import java.util.function.IntPredicate;

/**
 * @author twj
 * @description TODO
 * @time 2023/9/2^13:50:33
 */
public class LambdaDemo01 {
    public static void main(String[] args) {
        //普通方式
        // new Thread(new Runnable() {
        //     @Override
        //     public void run() {
        //         System.out.println("新线程中run方法被执行了");
        //     }
        // }).start();

        //lambda方式
        // new Thread(() -> {
        //     System.out.println("新线程中run方法被执行了");
        // }).start();

        int i = calculateNum(new IntBinaryOperator() {
            @Override
            public int applyAsInt(int left, int right) {
                return left + right;
            }
        });
        //lambda表达式
        int i1 = calculateNum((int left, int right) -> {
                    return left + right;
                }
        );
        System.out.println(i + " & " + i1);

        printNum(new IntPredicate() {
            @Override
            public boolean test(int value) {
                return value % 2 == 0;
            }
        });
        //lambda表达式
        printNum((value -> value % 2 == 0));

        Integer result = typeCover(new Function<String, Integer>() {
            @Override
            public Integer apply(String s) {
                return Integer.valueOf(s);
            }
        });
        System.out.println(result);

        Integer result1 = typeCover((String s) -> Integer.valueOf(s));
        System.out.println(result1);

        String s = typeCover(new Function<String, String>() {
            @Override
            public String apply(String s) {
                return s + "牛子";
            }
        });
        System.out.println(s);

        String s1 = typeCover((String str) -> str + "牛子");
        System.out.println(s1);

        foreachArr(new IntConsumer() {
            @Override
            public void accept(int value) {
                System.out.println(value);
            }
        });
        foreachArr(value -> System.out.println(value));

    }

    public static void foreachArr(IntConsumer consumer) {
        int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        for (int i : arr) {
            consumer.accept(i);
        }
    }

    public static <R> R typeCover(Function<String, R> function) {
        String str = "1235";
        R result = function.apply(str);
        return result;
    }

    public static void printNum(IntPredicate predicate) {
        int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        for (int i : arr) {
            if (predicate.test(i)) {
                System.out.println(i);
            }
        }
    }

    public static int calculateNum(IntBinaryOperator operator) {
        int a = 10;
        int b = 20;
        return operator.applyAsInt(a, b);
    }
}
